{% extends "base.html" %}

{% block title %}用户管理 - MinerU 文档解析系统{% endblock %}

{% block page_title %}用户管理{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 用户统计 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">总用户数</p>
                    <p class="text-2xl font-bold text-gray-800" id="totalUsers">0</p>
                </div>
                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-users text-blue-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">活跃用户</p>
                    <p class="text-2xl font-bold text-gray-800" id="activeUsers">0</p>
                </div>
                <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-user-check text-green-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">管理员</p>
                    <p class="text-2xl font-bold text-gray-800" id="adminUsers">0</p>
                </div>
                <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-user-shield text-purple-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">今日新增</p>
                    <p class="text-2xl font-bold text-gray-800" id="todayUsers">0</p>
                </div>
                <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-user-plus text-orange-600 text-xl"></i>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
                <button id="addUserBtn" class="btn-primary text-white px-4 py-2 rounded-md hover:bg-blue-700">
                    <i class="fas fa-plus mr-2"></i>添加用户
                </button>
                <button id="refreshUsersBtn" class="text-blue-600 hover:text-blue-800">
                    <i class="fas fa-sync-alt mr-2"></i>刷新
                </button>
            </div>
            
            <div class="flex items-center space-x-4">
                <input type="text" id="searchUsersInput" placeholder="搜索用户名或邮箱..." 
                       class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <select id="roleFilter" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">所有角色</option>
                    <option value="admin">管理员</option>
                    <option value="user">普通用户</option>
                </select>
            </div>
        </div>
    </div>
    
    <!-- 用户列表 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">用户列表</h3>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务数</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody id="usersTableBody" class="bg-white divide-y divide-gray-200">
                    <tr>
                        <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                            <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                            <p>加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加/编辑用户模态框 -->
<div id="userModal" class="modal fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden" data-backdrop="static" data-keyboard="false">
    <div class="relative top-20 mx-auto p-5 border w-11/12 max-w-md shadow-lg rounded-md bg-white" onclick="event.stopPropagation()">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800" id="userModalTitle">添加用户</h3>
                <button onclick="closeUserModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="userForm" class="space-y-4">
                <input type="hidden" id="userId">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                    <input type="text" id="username" required minlength="3" maxlength="50"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <p class="text-xs text-gray-500 mt-1">用户名长度必须在3-50个字符之间</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                    <input type="email" id="email" required 
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
                    <input type="password" id="password" minlength="6"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <p class="text-xs text-gray-500 mt-1">密码长度至少6个字符，编辑时留空表示不修改密码</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">角色</label>
                    <select id="role" required 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="user">普通用户</option>
                        <option value="admin">管理员</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
                    <select id="isActive" required 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="true">激活</option>
                        <option value="false">禁用</option>
                    </select>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeUserModal()" 
                            class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                        取消
                    </button>
                    <button type="submit" 
                            class="btn-primary text-white px-4 py-2 rounded-md hover:bg-blue-700">
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentEditingUser = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadUsers();
    loadUserStats();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    document.getElementById('addUserBtn').addEventListener('click', showAddUserModal);
    document.getElementById('refreshUsersBtn').addEventListener('click', () => {
        loadUsers();
        loadUserStats();
    });
    document.getElementById('searchUsersInput').addEventListener('input', debounce(loadUsers, 500));
    document.getElementById('roleFilter').addEventListener('change', loadUsers);
    document.getElementById('userForm').addEventListener('submit', saveUser);
}

// 加载用户列表
async function loadUsers() {
    try {
        const search = document.getElementById('searchUsersInput').value;
        const role = document.getElementById('roleFilter').value;
        
        let url = '/api/v1/admin/users';
        const params = new URLSearchParams();
        if (search) params.append('search', search);
        if (role) params.append('role', role);
        if (params.toString()) url += '?' + params.toString();
        
        const response = await apiRequest(url);
        updateUsersTable(response.items || []);  // 修复：将 response.users 改为 response.items
    } catch (error) {
        console.error('加载用户列表失败:', error);
        document.getElementById('usersTableBody').innerHTML = `
            <tr>
                <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                    <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                    <p>加载失败</p>
                </td>
            </tr>
        `;
    }
}

// 加载用户统计
async function loadUserStats() {
    try {
        const response = await apiRequest('/api/v1/admin/users/stats');
        document.getElementById('totalUsers').textContent = response.total || 0;
        document.getElementById('activeUsers').textContent = response.active || 0;
        document.getElementById('adminUsers').textContent = response.admins || 0;
        document.getElementById('todayUsers').textContent = response.today || 0;
    } catch (error) {
        console.error('加载用户统计失败:', error);
    }
}

// 更新用户表格
function updateUsersTable(users) {
    const tbody = document.getElementById('usersTableBody');
    
    if (users.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                    <i class="fas fa-inbox text-2xl mb-2"></i>
                    <p>暂无用户</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = users.map(user => `
        <tr class="hover:bg-gray-50">
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                    <img src="/static/images/avatars/avatar_${String((user.id % 100) + 1).padStart(3, '0')}.jpg" alt="${user.username}" 
                         class="w-10 h-10 rounded-full mr-3">
                    <div>
                        <div class="text-sm font-medium text-gray-800">${user.username}</div>
                        <div class="text-sm text-gray-500">ID: ${user.id}</div>
                    </div>
                </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800">${user.email}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                    user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
                }">
                    <i class="fas fa-${user.role === 'admin' ? 'user-shield' : 'user'} mr-1"></i>
                    ${user.role === 'admin' ? '管理员' : '普通用户'}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                    user.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                }">
                    <i class="fas fa-${user.is_active ? 'check' : 'times'} mr-1"></i>
                    ${user.is_active ? '激活' : '禁用'}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${formatDate(user.created_at)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800">${user.task_count || 0}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button onclick="editUser(${user.id})" class="text-blue-600 hover:text-blue-900 mr-3">
                    <i class="fas fa-edit"></i>
                </button>
                <button onclick="deleteUser(${user.id})" class="text-red-600 hover:text-red-900">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

// 显示添加用户模态框
function showAddUserModal() {
    currentEditingUser = null;
    document.getElementById('userModalTitle').textContent = '添加用户';
    document.getElementById('userForm').reset();
    document.getElementById('userId').value = '';
    document.getElementById('password').required = true;
    document.getElementById('userModal').classList.remove('hidden');
}

// 编辑用户
async function editUser(userId) {
    try {
        const user = await apiRequest(`/api/v1/admin/users/${userId}`);
        currentEditingUser = user;
        
        document.getElementById('userModalTitle').textContent = '编辑用户';
        document.getElementById('userId').value = user.id;
        document.getElementById('username').value = user.username;
        document.getElementById('email').value = user.email;
        document.getElementById('password').value = '';
        document.getElementById('password').required = false;
        document.getElementById('role').value = user.role;
        document.getElementById('isActive').value = user.is_active.toString();
        
        document.getElementById('userModal').classList.remove('hidden');
    } catch (error) {
        console.error('获取用户信息失败:', error);
        showNotification('获取用户信息失败', 'error');
    }
}

// 删除用户
async function deleteUser(userId) {
    if (!confirm('确定要删除这个用户吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        await apiRequest(`/api/v1/admin/users/${userId}`, { method: 'DELETE' });
        showNotification('用户删除成功', 'success');
        loadUsers();
        loadUserStats();
    } catch (error) {
        console.error('删除用户失败:', error);
        showNotification('删除用户失败', 'error');
    }
}

// 保存用户
async function saveUser(e) {
    e.preventDefault();
    
    const userId = document.getElementById('userId').value;
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const role = document.getElementById('role').value;
    const isActive = document.getElementById('isActive').value === 'true';
    
    const userData = {
        username: username,
        email: email,
        role: role,
        is_active: isActive
    };
    
    if (password) {
        userData.password = password;
    }
    
    try {
        let response;
        if (userId) {
            // 编辑用户
            response = await apiRequest(`/api/v1/admin/users/${userId}`, {
                method: 'PUT',
                body: JSON.stringify(userData)
            });
            showNotification('用户更新成功', 'success');
        } else {
            // 添加用户
            response = await apiRequest('/api/v1/admin/users', {
                method: 'POST',
                body: JSON.stringify(userData)
            });
            showNotification('用户添加成功', 'success');
        }
        
        closeUserModal();
        loadUsers();
        loadUserStats();
    } catch (error) {
        console.error('保存用户失败:', error);
        
        // 检查特定错误类型
        if (error.message && error.message.includes('Username already exists')) {
            showNotification('用户名已存在，请使用其他用户名', 'error');
        } else if (error.message && error.message.includes('Email already exists')) {
            showNotification('邮箱已存在，请使用其他邮箱', 'error');
        } else if (error.message && error.message.includes('ensure this value has at least 3 characters')) {
            showNotification('用户名长度至少需要3个字符', 'error');
        } else if (error.message && error.message.includes('ensure this value has at least 6 characters')) {
            showNotification('密码长度至少需要6个字符', 'error');
        } else if (error.message && error.message.includes('valid email')) {
            showNotification('请输入有效的邮箱地址', 'error');
        } else {
            // 显示通用错误消息，包含具体错误详情
            showNotification(`保存用户失败: ${error.message}`, 'error');
        }
    }
}

// 关闭用户模态框
function closeUserModal() {
    document.getElementById('userModal').classList.add('hidden');
    currentEditingUser = null;
}

// 防止点击模态框外部区域关闭
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('userModal');
    
    // 防止点击背景关闭模态框
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            e.preventDefault();
            e.stopPropagation();
        }
    });
    
    // 防止ESC键关闭模态框
    modal.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            e.preventDefault();
            e.stopPropagation();
        }
    });
});

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}
</script>
{% endblock %}